function throttle (func, interval) {
    let lastTime = 0;
    return function(...args) {
        const now = Date.now();
        console.log(now - lastTime, interval )
        if (now - lastTime >= interval) {
            func.apply(this, args);
            lastTime = now;
        }
    };
}

export default function myPlugin(options = {}) {
    return (store) => {
        const { paths = [], key = 'vuex-state' , storage = localStorage } = options;
        const STRONG_NAME = key
        // 1. 初始化时从 localStorage 恢复数据
        const savedState = storage.getItem(STRONG_NAME)
        if (savedState) {
            const parsedState = JSON.parse(savedState)
            const targetState = paths.reduce((pr, cur) => {
                if (parsedState[cur]) {
                    pr[cur] = parsedState[cur]
                }
                return pr
            }, {})
            store.replaceState({
                ...store.state,
                ...targetState
            })
        }

        // 2. 订阅 mutation 变化，保存到 localStorage
        store.subscribe(throttle((mutaion, state) => {
            const persistData = paths.reduce((obj, path) => {
                obj[path] = state[path]
                return obj
            }, {})
            storage.setItem(STRONG_NAME, JSON.stringify(persistData))
        }, 1000))
    }
}